package com.hm.service.aop.error;

import com.hm.service.utils.response.ResponseUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 * 从Controller进来
 */

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = {Exception.class})
    public String exceptionHandler(HttpServletRequest request, Exception e) {
        StackTraceElement[] stackTrace = e.getStackTrace();
        String methodName = stackTrace[0].getMethodName();
        logger.error("{}==>Exception:{}", request.getRequestURL(), e.getMessage());
        logger.error("==>异常方法名:{}", methodName);
        logger.error("==>异常类路径:{}", e.getClass().getName());
        return ResponseUtils.generateFailForCode("1000", "Exception:" + e.getMessage());
    }

    @ExceptionHandler(value = {RuntimeException.class})
    public String RuntimeExceptionHandler(HttpServletRequest request, Exception e) {
        StackTraceElement[] stackTrace = e.getStackTrace();
        String methodName = stackTrace[0].getMethodName();
        String className = stackTrace[0].getClassName();
        logger.error("{}==>RuntimeException:{}", request.getRequestURL(), e.getMessage());
        logger.error("1==>异常方法名:{}", methodName);
        logger.error("1==>异常类路径:{}", className);
        return ResponseUtils.generateFailForCode("10001", "RuntimeException:" + e.getMessage());
    }

}
